package com.rz.htk.config.jobhandler;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rz.htk.order.entity.Order;
import com.rz.htk.order.service.IOrderService;
import com.rz.htk.order.task.OrderTask;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@JobHandler(value = "youSuTrackHandler")
@Component
public class YouSuTrackHandler extends IJobHandler {
    private Logger logger = LoggerFactory.getLogger("YouSuTrackHandler");

    @NacosValue(value = "${enableScheduled}", autoRefreshed = true)
    private boolean enableScheduled;
    @Resource
    private IOrderService IOrderService;
    @Resource
    private OrderTask orderTask;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        if(enableScheduled){
            try {
                XxlJobLogger.log("开始推送轨迹至优速");
                QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("prd_code","HTK_P0010","HTK_P0011");
                queryWrapper.eq("track_success",1);
                queryWrapper.eq("push_yousu_flag",0);
                Page<Order> firstPage = new Page<>(1, 1);
                IPage<Order> pageList = IOrderService.page(firstPage, queryWrapper);
                pushTrackToYousu(pageList.getRecords());
                long totalPages = pageList.getPages();
                if(totalPages>1){
                    for(int i=1;i<=totalPages;i++){
                        Page<Order> page = new Page<>(i, 1);
                        IPage<Order> list = IOrderService.page(page, queryWrapper);
                        pushTrackToYousu(list.getRecords());
                    }
                }

            }catch (Exception e){
                logger.error("推送轨迹至优速报错 {}",e.getMessage());
                XxlJobLogger.log("推送轨迹至优速报错"+e.getMessage());
            }
        }
        return SUCCESS;
    }

    private void pushTrackToYousu(List<Order> list){
        list.forEach(order->{
            if(order.getTrackSuccess().equals(1)){
                orderTask.pushTrackToYouSu(order.getAfterCode());
            }
        });
    }
}
